﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using TimKen.BussLogic;
using TimKen.DataEntity;
using System.IO;
using TimKen.App;

namespace TimKen.Web.Admin.ProductCategory
{
    public partial class ProductCategory_Add : TimKen.App.AdminPage
    {
        private PCategoryManager categoryManager = new PCategoryManager();
        private string toadd = "├";

        private string categoryId = null;
        public override string ActionCode
        {
            get
            {
                return "89";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.ddlParentID.Items.Clear();
                this.ddlParentID.Items.Add(new ListItem(GetLangString("SetAsRootCategory"), "0"));
                BindProductCategory("0");

                Session["file_info"] = null;

                ///编辑分类
                if (Request.QueryString["categoryId"] != null)
                {
                    categoryId = Request.QueryString["categoryId"];
                    string Act = string.Empty;
                    if (Request.QueryString["Act"] != null)
                        Act = Request.QueryString["Act"];
                    if (Act.ToLower().Equals("edit"))
                    {
                        if (TypeParse.IsNumeric(categoryId))
                            BindCategoryData(Convert.ToInt32(categoryId));
                    }
                    else if (Act.ToLower().Equals("add"))
                    {
                        if (TypeParse.IsNumeric(categoryId) && Convert.ToInt32(categoryId) > 0)
                        {
                            this.ddlParentID.SelectedValue = categoryId;
                        }
                        this.chbIsLeaf.Enabled = true;
                        this.btnChangeIsLeaf.Visible = false;
                        this.imgCagegoryImage.Visible = false;
                    }
                }
                else
                {
                    this.chbIsLeaf.Enabled = true;
                    this.btnChangeIsLeaf.Visible = false;
                    this.imgCagegoryImage.Visible = false;
                }
                BindResources();
            }
        }

        private void BindCategoryData(int categoryId)
        {
            this.chbIsLeaf.Enabled = false;
            PCategory categoryCn = categoryManager.GetModel(categoryId, LanguageEnum.Chinese);
            PCategory categoryEn = categoryManager.GetModel(categoryId, LanguageEnum.English);


            txtCategoryNameCn.Text = categoryCn.CategoryName;
            txtCategoryNameEn.Text = categoryEn.CategoryName;


            //如果没有图片,则不显示
            if (string.IsNullOrEmpty(categoryCn.CategoryImage))
                this.imgCagegoryImage.Visible = false;

            else
                this.imgCagegoryImage.ImageUrl = categoryCn.CategoryImage;


            for (int i = 0; i < this.ddlParentID.Items.Count; i++)
            {
                if (this.ddlParentID.Items[i].Value == categoryCn.ParentID.ToString())
                    this.ddlParentID.Items[i].Selected = true;
            }
            this.btnChangeIsLeaf.Text = categoryCn.IsLeaf ? GetLangString("ChangeToNonLeafCategory") : GetLangString("ChangeToLeafCategory");
            // this.ddlParentID.Enabled = false;

            for (int j = 0; j < this.ddlTemplate.Items.Count; j++) {
                if (this.ddlTemplate.Items[j].Value == categoryCn.SortOrder.ToString())
                    this.ddlTemplate.Items[j].Selected = true;
            }

            chbIsLeaf.Checked = categoryCn.IsLeaf;
            this.txtDateAdded.Text = categoryCn.DateAdded.ToString();
            this.txtLastModified.Text = categoryCn.LastModified.ToString();
            this.txtDescriptionCn.Text = categoryCn.Description;
            this.txtDescriptionEn.Text = categoryEn.Description;
        }

        /// <summary>
        /// 绑定产品分类分级选择列表
        /// </summary>
        private void BindProductCategory(string parentId)
        {
            DataSet ds = categoryManager.GetList(LanguageWhereStr + " AND ParentID=" + parentId);

            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    this.ddlParentID.Items.Add(new ListItem(toadd + " " + dr["CategoryName"].ToString(), dr["CategoryID"].ToString()));
                    toadd += "─┴";
                    BindProductCategory(dr["CategoryID"].ToString());
                    toadd = toadd.Substring(0, toadd.Length - 2);
                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            PCategory categoryCn = new PCategory();
            categoryCn.CategoryName = this.txtCategoryNameCn.Text;
            categoryCn.CategoryImage = this.imgCagegoryImage.ImageUrl;
            categoryCn.LanguageID = 1;
            categoryCn.ParentID = Convert.ToInt32(this.ddlParentID.SelectedValue);
            categoryCn.SortOrder = Convert.ToInt32(this.ddlTemplate.SelectedItem.Value);
            categoryCn.IsLeaf = chbIsLeaf.Checked;
            categoryCn.Description = this.txtDescriptionCn.Text;

            PCategory categoryEn = new PCategory();
            categoryEn.CategoryName = this.txtCategoryNameEn.Text;
            categoryEn.CategoryImage = this.imgCagegoryImage.ImageUrl;
            categoryEn.LanguageID = 2;
            categoryEn.ParentID = Convert.ToInt32(this.ddlParentID.SelectedValue);
            categoryEn.SortOrder = Convert.ToInt32(this.ddlTemplate.SelectedItem.Value);
            categoryEn.IsLeaf = chbIsLeaf.Checked;
            categoryEn.Description = this.txtDescriptionEn.Text;

            bool actionSuccess = false;
            string alertMessage = "";
            ///更新
            if (Request.QueryString["categoryId"] != null)
            {
                int categoryId = Convert.ToInt32(Request.QueryString["categoryId"]);
                categoryCn.CategoryID = categoryId;
                categoryEn.CategoryID = categoryId;
                actionSuccess = categoryManager.Update(categoryCn, categoryEn);
                alertMessage = categoryManager.ValidMessage;
                Alert(alertMessage);
            }
            else
            {
                actionSuccess = categoryManager.Add(categoryCn, categoryEn) > 0;
                alertMessage = categoryManager.ValidMessage;
                if (actionSuccess)
                {
                    if (categoryCn.IsLeaf) {
                        Alert("为叶子分类添加属性", "../PAttribute/CategoryOption_List.aspx?CategoryID=" + categoryCn.CategoryID);
                    }
                    else
                    Alert(alertMessage, "ProductCategory_List.aspx");
                }
                else
                    Alert(alertMessage);
            }
        }

        private void BindResources()
        {
            this.btnSubmit.Text = GetLangString("Save");
            this.btnUpload.Value = GetLangString("Upload");
            this.btnDelete.Text = GetLangString("Delete");
        }

        protected void btnChangeIsLeaf_Click(object sender, EventArgs e)
        {
            if (categoryManager.ChangeIsLeaf(Convert.ToInt32(Request.QueryString["categoryId"]), chbIsLeaf.Checked))
            {
                chbIsLeaf.Checked = !chbIsLeaf.Checked;
                btnChangeIsLeaf.Text = chbIsLeaf.Checked ? GetLangString("ChangeToNonLeafCategory") : GetLangString("ChangeToLeafCategory");
            }
            else
            {
                Alert(categoryManager.ValidMessage);
            }
        }


        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.txtCategoryImage.Text != "")
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(PhysicalUploadFilePathForProduct + this.txtCategoryImage.Text);
                if (fileInfo.Exists)
                {
                    try
                    {
                        fileInfo.Delete();

                        this.imgCagegoryImage.Visible = false;
                        this.imgCagegoryImage.ImageUrl = "";
                        this.txtCategoryImage.Text = "";
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("删除失败,错误信息" + ex.Message);
                    }
                }

            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            this.imgCagegoryImage.Visible = true;
            this.imgCagegoryImage.ImageUrl = UploadFilePathForProduct + this.txtCategoryImage.Text;
        }
    }
}
